package ph.com.gs3.formalistics.model.vo.parsers;

import java.util.Iterator;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import ph.com.gs3.formalistics.global.constants.StarMark;
import ph.com.gs3.formalistics.global.utilities.Serializer;
import ph.com.gs3.formalistics.global.utilities.TextUtilities;
import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.vo.business.User;
import ph.com.gs3.formalistics.model.vo.business.document.DisplayReadyAction;
import ph.com.gs3.formalistics.model.vo.business.document.DocumentSummary;
import ph.com.gs3.formalistics.model.vo.business.document.SubmitReadyAction;
import ph.com.gs3.formalistics.model.vo.view.DocumentDisplayItem;
import ph.com.gs3.formalistics.model.vo.view.DocumentDisplayItem.TargetDocument;

public class DocumentDisplayItemParser {

	public static final String TAG = DocumentDisplayItemParser.class.getSimpleName();

	public static DocumentDisplayItem parseDocumentSummary(DocumentSummary document,
	        User currentUser) {

		DocumentDisplayItem documentDisplayItem = new DocumentDisplayItem();

		documentDisplayItem.setDocumentId(document.getDocumentId());
		documentDisplayItem.setDocumentAuthorId(document.getAuthorId());
		documentDisplayItem.setDocumentProcessorId(document.getProcessorId());
		documentDisplayItem.setFormId(document.getFormId());

		documentDisplayItem.setStarred(document.getStarMark() == StarMark.STARRED);
		documentDisplayItem.setOutgoing(false);

		documentDisplayItem.setShowActionsButton(document.getProcessorId() == currentUser.getId());
		documentDisplayItem.setShowStarButton(true);
		documentDisplayItem.setShowCommentButton(true);

		documentDisplayItem.setHeader(document.getFormName());
		documentDisplayItem.setDate(document.getDateUpdatedString());
		documentDisplayItem.setSubheader(document.getAuthorDisplayName());
		documentDisplayItem.setContentsHeader("Tracking Number: " + document.getTrackingNumber());
		documentDisplayItem.setContentsBody(generateDocumentFieldPreview(document
		        .getFieldValuesJSON()));

		documentDisplayItem.setFooterHeader("Status");
		documentDisplayItem.setFooterBody(document.getStatus());

		documentDisplayItem.setAvailableActions(document.getDocumentActions());
		documentDisplayItem.setTargetDocument(TargetDocument.ORIGINAL_DOCUMENT);

		return documentDisplayItem;

	}

	public static DocumentDisplayItem parseDisplayReadyAction(DisplayReadyAction displayReadyAction) {

		DocumentDisplayItem documentDisplayItem = new DocumentDisplayItem();

		documentDisplayItem.setFormId(displayReadyAction.getFormId());
		documentDisplayItem.setDocumentId(displayReadyAction.getDocumentId());
		documentDisplayItem.setDocumentAuthorId(displayReadyAction.getIssuedByUserId());
		documentDisplayItem.setDocumentProcessorId(0);

		documentDisplayItem.setStarred(displayReadyAction.getIsStarred() == StarMark.STARRED);
		documentDisplayItem.setOutgoing(true);

		documentDisplayItem.setShowActionsButton(false);
		documentDisplayItem.setShowStarButton(false);
		documentDisplayItem.setShowCommentButton(false);

		documentDisplayItem.setHeader(displayReadyAction.getFormName());
		documentDisplayItem.setDate(displayReadyAction.getDateIssued());

		String subHeader;

		if (displayReadyAction.getDocumentId() == 0) {
			subHeader = "Document: new document";
		} else {
			subHeader = "Document: " + displayReadyAction.getTrackingNumber();
		}

		if (displayReadyAction.getDocumentFieldUpdatesString() != null) {
			try {
				JSONObject contentsBody = new JSONObject(
				        displayReadyAction.getDocumentFieldUpdatesString());
				documentDisplayItem.setContentsBody(generateDocumentFieldPreview(contentsBody));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		documentDisplayItem.setSubheader(subHeader);
		documentDisplayItem.setFooterHeader("Issued Action(s)");

		List<String> issuedActions = displayReadyAction.getIssuedActions();
		if (issuedActions.contains(SubmitReadyAction.ACTION_NO_DOCUMENT_SUBMISSION)) {
			issuedActions.remove(SubmitReadyAction.ACTION_NO_DOCUMENT_SUBMISSION);
			documentDisplayItem.setTargetDocument(TargetDocument.ORIGINAL_DOCUMENT);
		} else {
			documentDisplayItem.setTargetDocument(TargetDocument.OUTGOING_ACTION);
		}

		documentDisplayItem.setFooterBody(Serializer.serializeList(issuedActions));

		return documentDisplayItem;
	}

	public static String generateDocumentFieldPreview(JSONObject fieldValues) {

		String contents = "";

		int keyCounter = 0;
		Iterator<String> iterator = fieldValues.keys();
		while (iterator.hasNext() && keyCounter < 3) {
			String key = iterator.next();
			try {
				String value = fieldValues.getString(key);

				if (value.trim().isEmpty()) {
					// Skip blank values
					continue;
				}

				if (value.contains("|^|")) {
					value = value.replace("|^|", ", ");
				}

				contents += TextUtilities.ellipsize(value, 32, 3) + "\n";
			} catch (JSONException e) {
				FLLogger.w(TAG, "Failed to read " + key + " for preview of a document summary.");
			}

			// keyCounter++;
		}

		// Trim the last new line
		contents = contents.substring(0, contents.length() - 1);

		return contents;

	}

}
